import CryptoJS from 'crypto-js'
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

//实现数字千分位格式
export function numberToCurrencyNo(value) {
  if (!value) return 0
  // 获取整数部分
  const intPart = Math.trunc(value)
  // 整数部分处理，增加,
  const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  // 预定义小数部分
  let floatPart = ''
  // 将数值截取为小数部分和整数部分
  const valueArray = value.toString().split('.')
  if (valueArray.length === 2) { // 有小数部分
    floatPart = valueArray[1].toString() // 取得小数部分
    return intPartFormat + '.' + floatPart
  }
  return intPartFormat + floatPart
}



//倒计时
export function showtime(startTime,nowTime) {
//     var nowtime = new Date();  //获取当前时间
    var lefttime = nowTime - startTime;  //距离结束时间的毫秒数
     var   leftd = Math.floor(lefttime/(1000*60*60*24));  //计算天数
      var  lefth = Math.floor(lefttime/(1000*60*60)%24);  //计算小时数
      var  leftm = Math.floor(lefttime/(1000*60)%60);  //计算分钟数
      var  lefts = Math.floor(lefttime/1000%60);  //计算秒数
      var day = leftd > 0 ?  leftd+"天" : '';
      var h =  lefth > 0 ? + lefth+'小时': '';
      var m = leftm  > 0 ?+ leftm+'分': '';
      if(day == 0 && h == 0 && m ==0){
       return day+h+m
      }else{
       return '一分钟内'
      }

}
/**
* 1加密：
* @param  data {加密的数据}
*/
export function encrypt(data) {
      return CryptoJS.AES.encrypt(
        data,
        CryptoJS.enc.Utf8.parse('crm@.moresu.com!'), {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        }).toString();
  }


export async function copyText(text) {
      try {
        // 现代API方案（优先尝试）
        if (navigator.clipboard && window.isSecureContext) {
          await navigator.clipboard.writeText(text);
          return;
        }
        // 传统方案（兼容旧浏览器和部分移动端）
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);

        // 处理iOS特殊行为
        if (navigator.userAgent.match(/ipad|iphone/i)) {
          const range = document.createRange();
          range.selectNodeContents(textarea);
          const selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
          textarea.setSelectionRange(0, 999999);
        } else {
          textarea.select();
        }

        document.execCommand('copy');
        document.body.removeChild(textarea);
      } catch (err) {
        console.error('复制失败:', err);
        throw new Error('无法访问剪贴板');
      }
    }
